#include "confirmdialog.h"

ConfirmDialog::ConfirmDialog(DbConnection *DB, QWidget *parent) :
    QDialog(parent),db(DB), staTe(0)
{
  QVBoxLayout *vlay = new QVBoxLayout;
  QHBoxLayout *main = new QHBoxLayout;
  inputCod.setEchoMode(QLineEdit::Password);
  showCode.setText(tr("Показывать код"));
  connect(&showCode,SIGNAL(stateChanged(int)),this,SLOT(stateChange(int)));
  QHBoxLayout *hlay = new QHBoxLayout;
  vlay->addWidget(&message);
  vlay->addWidget(&inputCod);
  vlay->addWidget(&showCode);
  hlay=new QHBoxLayout;
  hlay->addStretch();
  hlay->addWidget(&cnlBtn);
  hlay->addWidget(&okBtn);
  vlay->addLayout(hlay);
  connect(&cnlBtn,SIGNAL(clicked()),this,SLOT(reject()));
  connect(&okBtn,SIGNAL(clicked()),this,SLOT(onOkClick()));
  main->addWidget(&image);
  main->addLayout(vlay);
  setLayout(main);  
  setState(0);
  setFixedHeight(sizeHint().height());
  setFixedWidth(sizeHint().width()+40);
  setModal(true);
  setWindowTitle(tr("Подтверждение"));
  setWindowIcon(QIcon(":/check"));
}

void ConfirmDialog::onOkClick()
{
    switch(staTe)
    {
    case -1:{
            setState(0);
            inputCod.setFocus();
            inputCod.selectAll();
            break;
        }
    case 0:{
            if(check())
            {
                setState(1);
            }
            else
                setState(-1);
            break;
        }
    case 1:{
            accept();
        }
    }
}

void ConfirmDialog::setState(const int &State)
{
    switch(State)
    {
    case -1:{
            image.setPixmap(QPixmap(":/error"));
            inputCod.hide();
            showCode.hide();
            okBtn.setText(tr("Повторить"));
            okBtn.setFocus();
            cnlBtn.setText(tr("Отмена"));
            message.setText(tr("Неверный код подтверждения"));
            cnlBtn.show();
            break;
        }
    case 0:{
            image.setPixmap(QPixmap(":/pass"));
            inputCod.show();
            showCode.show();
            message.setText(tr("Введите код подтверждения"));
            okBtn.setText(tr("Готово"));
            okBtn.setFocus();
            cnlBtn.setText(tr("Отмена"));
            cnlBtn.show();
            break;
        }
    case 1:{
            image.setPixmap(QPixmap(":/success"));
            inputCod.hide();
            showCode.hide();
            message.setText(tr("Подтверждение прошло успешно"));
            okBtn.setText(tr("Продолжить"));
            okBtn.setFocus();
            cnlBtn.hide();
        }
    }
    staTe=State;
}

bool ConfirmDialog::check() const
{
    DbConnection::QueryResult result = db->execute(tr("select =schema=.ex_check_code('%1'::text)").arg(inputCod.text()));
    return result.at(0,0).toBool();
}

void ConfirmDialog::stateChange(int state)
{
    if(state==Qt::Unchecked) inputCod.setEchoMode(QLineEdit::Password);
    if(state==Qt::Checked) inputCod.setEchoMode(QLineEdit::Normal);
}
